package com.sun.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.enums.HttpEnum;
import com.sun.mapper.PurchaseOrderDetailsMapper;
import com.sun.mapper.PurchaseOrdersMapper;
import com.sun.pojo.dto.PurchaseOrderDetailsDTO;
import com.sun.pojo.dto.PurchaseOrderDetailsDeliverDTO;
import com.sun.pojo.entity.Products;
import com.sun.pojo.entity.PurchaseOrderDetails;
import com.sun.pojo.entity.PurchaseOrders;
import com.sun.pojo.entity.Suppliers;
import com.sun.pojo.vo.ProductsDisplayVO;
import com.sun.pojo.vo.PurchaseOrderDetailsSelectStatusVO;
import com.sun.pojo.vo.R;
import com.sun.service.ProductsService;
import com.sun.service.PurchaseOrderDetailsService;
import com.sun.service.SuppliersService;
import com.sun.utils.DingDingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购明细表 记录每个采购订单的具体商品信息。(PurchaseOrderDetails)表服务实现类
 *
 * @author makejava
 * @since 2024-10-25 08:18:16
 */
@Service("purchaseOrderDetailsService")
public class PurchaseOrderDetailsServiceImpl implements PurchaseOrderDetailsService {
    @Autowired
    PurchaseOrderDetailsMapper purchaseOrderDetailsMapper;
    @Autowired
    ProductsService productsService;
    @Autowired
    PurchaseOrdersMapper purchaseOrdersMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param orderId 主键
     * @return 实例对象
     */
    @Override
    public PurchaseOrderDetails queryById(String orderId) {
        return purchaseOrderDetailsMapper.queryById(orderId);
    }

    /**
     * 分页查询
     *
     * @param purchaseOrderDetails 筛选条件
     * @param pageNum              分页对象
     * @return 查询结果
     */
    @Override
    public PageInfo<PurchaseOrderDetails> queryByPage(PurchaseOrderDetails purchaseOrderDetails, Integer pageNum) {
        PageHelper.startPage(pageNum, 5);
        List<PurchaseOrderDetails> list = purchaseOrderDetailsMapper.queryAllByLimit(purchaseOrderDetails);
        PageInfo<PurchaseOrderDetails> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 新增数据
     *
     * @param purchaseOrderDetails 实例对象
     * @return 实例对象
     */
    @Override
    public R insert(List<PurchaseOrderDetailsDTO> purchaseOrderDetails) {
        // 使用表达式吧dto数据放入
        List<PurchaseOrderDetails> list = new ArrayList<>();
        String times = String.valueOf(System.currentTimeMillis());
        float moneys = 0;//总金额
        for (PurchaseOrderDetailsDTO purchaseOrderDetailDTO : purchaseOrderDetails) {
            PurchaseOrderDetails details = new PurchaseOrderDetails();
            details.setProductId(purchaseOrderDetailDTO.getProductId());
            details.setQuantity(purchaseOrderDetailDTO.getQuantity());
            details.setUnitPrice(purchaseOrderDetailDTO.getUnitPrice());
            details.setCreatedBy(purchaseOrderDetailDTO.getCreatedBy());
            details.setOrderId(times);
            float f = details.getQuantity();
            float p = details.getUnitPrice();
            moneys += p * f;
            list.add(details);
        }

        // 根据订单商品ID 查询供应商ID
        List<Integer> productsIdList = new ArrayList<>();
        for (PurchaseOrderDetails purchaseOrderDetail : list) {
            ProductsDisplayVO products = productsService.queryById(purchaseOrderDetail.getProductId());
            productsIdList.add(products.getSupplierId());
        }




        // 创建订单数据
        List<PurchaseOrders> purchaseOrders = new ArrayList<>();
        int i = 0;
        for (PurchaseOrderDetails purchaseOrderDetail : list) {
            PurchaseOrders purchaseOrder = new PurchaseOrders();
            purchaseOrder.setOrderId(times);
            purchaseOrder.setSupplierId(productsIdList.get(i++));
            purchaseOrder.setCreatedBy(purchaseOrderDetail.getCreatedBy());
            purchaseOrder.setTotalAmount(moneys);
            purchaseOrder.setStatus(0);
            purchaseOrders.add(purchaseOrder);
        }

        if (purchaseOrderDetailsMapper.insertBatch(list)>0){
            if (purchaseOrdersMapper.insertBatch(purchaseOrders)>0){
                DingDingUtil dingDingUtil = new DingDingUtil();
                dingDingUtil.getDingDingText("您有新的订单，请发货");
                return R.success("新增成功");
            }
        }
        return R.fail(HttpEnum.WARN.getCode(), "新增失败");
    }

    /**
     * 修改数据
     *
     * @param purchaseOrderDetails 实例对象
     * @return 实例对象
     */
    @Override
    public R update(PurchaseOrderDetails purchaseOrderDetails) {
        if (purchaseOrderDetailsMapper.update(purchaseOrderDetails) > 0) {
            return R.success("修改成功");
        }
        return R.fail(HttpEnum.WARN.getCode(), "修改失败");
    }

    /**
     * 通过主键删除数据
     *
     * @param orderId 主键
     * @return 是否成功
     */
    @Override
    public R deleteById(String orderId) {
        if (purchaseOrderDetailsMapper.deleteById(orderId) > 0) {
            return R.success("删除成功");
        }
        return R.fail(HttpEnum.WARN.getCode(), "删除失败");
    }

    /**
     * 通过主键查询订单
     *
     * @param orderId 主键
     * @return 是否成功
     */
    @Override
    public R selectDetailsAll(String orderId) {
        return R.success(purchaseOrderDetailsMapper.selectDetailsAll(orderId));
    }

    @Override
    public R deliver(PurchaseOrderDetailsDeliverDTO dto) {
        if (purchaseOrderDetailsMapper.deliver(dto)>0){
            return R.success(dto.getOrderId());
        }else {
            return R.fail(HttpEnum.WARN.getCode(), "发货失败");
        }
    }

    @Override
    public R selectStatus2(String productName2) {
        List<PurchaseOrderDetailsSelectStatusVO> psvo = purchaseOrderDetailsMapper.selectStatus2(productName2);

        // 使用 Map 来存储每个 productId 的总数量、productName 和 imageUrl
        Map<Integer, ProductQuantity> productQuantityMap = new HashMap<>();

        for (PurchaseOrderDetailsSelectStatusVO item : psvo) {
            int productId = item.getProductId();
            int quantity = item.getQuantity();
            String productName = item.getProductName();
            String imageUrl = item.getImageUrl(); // 获取 imageUrl

            if (!productQuantityMap.containsKey(productId)) {
                productQuantityMap.put(productId, new ProductQuantity(productName, quantity, imageUrl));
            } else {
                ProductQuantity existing = productQuantityMap.get(productId);
                existing.setQuantity(existing.getQuantity() + quantity);
            }
        }

        // 将 Map 转换为 List<PurchaseOrderDetailsSelectStatusVO>
        List<PurchaseOrderDetailsSelectStatusVO> resultList = productQuantityMap.entrySet().stream()
                .map(entry -> new PurchaseOrderDetailsSelectStatusVO(null, entry.getValue().getQuantity(), entry.getValue().getProductName(), entry.getKey(), entry.getValue().getImageUrl()))
                .collect(Collectors.toList());


        return R.success(resultList); // 根据实际需求返回适当的值
    }

    @Override
    public R selectBySupplierId(String supplierId , Integer status) {
        if (status == 0){
            return R.success(purchaseOrderDetailsMapper.selectBySupplierNoId(supplierId));
        }else {
            return R.success(purchaseOrderDetailsMapper.selectBySupplierId(supplierId));
        }
    }

    @Override
    public R selectSuppliersMoneys(String supplierId, String updatedBy) {
        return R.success(purchaseOrderDetailsMapper.selectSuppliersMoneys(supplierId,updatedBy));
    }


    private static class ProductQuantity {
        private String productName;
        private int quantity;
        private String imageUrl; // 添加 imageUrl 字段

        public ProductQuantity(String productName, int quantity, String imageUrl) {
            this.productName = productName;
            this.quantity = quantity;
            this.imageUrl = imageUrl;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public int getQuantity() {
            return quantity;
        }

        public void setQuantity(int quantity) {
            this.quantity = quantity;
        }

        public String getImageUrl() {
            return imageUrl;
        }

        public void setImageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
        }
    }

}
